<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>实名信息</span>
        </div>
      </template>
      <div class="tip">
        <svg
          class="icon"
          height="16"
          p-id="3735"
          t="1719565432454"
          version="1.1"
          viewBox="0 0 1024 1024"
          width="16"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M508.8 44.8c-256 0-464 208-464 464s208 464 464 464 464-208 464-464S764.8 44.8 508.8 44.8zM508.8 924.8c-230.4 0-416-185.6-416-416s185.6-416 416-416 416 185.6 416 416S739.2 924.8 508.8 924.8z"
            p-id="3736"
          ></path>
          <path
            d="M521.6 652.8c12.8 0 22.4-9.6 22.4-22.4l0-428.8c0-12.8-9.6-22.4-22.4-22.4-12.8 0-22.4 9.6-22.4 22.4l0 428.8C496 640 508.8 652.8 521.6 652.8z"
            p-id="3737"
          ></path>
          <path
            d="M521.6 748.8m-35.2 0a1.1 1.1 0 1 0 70.4 0 1.1 1.1 0 1 0-70.4 0Z"
            p-id="3738"
          ></path>
        </svg>
        完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步，建议提前实名认证。
      </div>
      <!--   认证信息  v-if="userInfo.authStatus === 1" -->
      <div class="">
        <el-descriptions
          :column="1"
          :size="'default'"
          border
          direction="horizontal"
        >
          <el-descriptions-item :width="30" label="用户姓名">
            >{{ userInfo.name }}
          </el-descriptions-item>
          <el-descriptions-item :width="30" label="证件类型"
            >{{ userInfo.certificatesType === "10" ? "身份证" : "户口本" }}
          </el-descriptions-item>
          <el-descriptions-item :width="30" label="证件号码">
            {{ userInfo.certificatesNo }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <!--  用户未认证结构    -->
      <div class="userInfo">
        <el-form :model="userAuthVo" :rules="rules" formlabel-width="80 ref=">
          <el-form-item label="用户姓名" prop="name">
            <el-input v-model="userAuthVo.name" placeholder="请输入用户姓名" />
          </el-form-item>
          <el-form-item label="证件类型" prop="certificatesType">
            <el-select
              v-model="userAuthVo.certificatesType"
              placeholder="请选择证件类型"
            >
              <el-option
                v-for="item in certificateTypes"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码" prop="certificatesNo">
            <el-input
              v-model="userAuthVo.certificatesNo"
              placeholder="请输入证件号码"
            />
          </el-form-item>
          <el-form-item label="上传证件">
            <el-upload
              ref="uploadRef"
              :limit="1"
              :on-exceed="fileNumHandler"
              :on-preview="previewFile"
              :on-remove="fileRemove"
              :on-success="uploadSuccess"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              list-type="picture-card"
            >
              <img
                src="@/assets/images/card.png"
                style="width: 100%; height: 100%"
              />
            </el-upload>
            <el-dialog v-model="isPreview">
              <img
                :src="userAuthVo.certificatesUrl"
                alt="身份证自拍图"
                style="width: 100%; height: 100%"
                w-full
              />
            </el-dialog>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="authUserInfo">提交</el-button>
            <el-button @click="reset">重写</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts" name="Certification" setup>
import { onMounted, reactive, ref } from "vue";
import { doGetUserInfo, doUserAuth } from "@/api/user.ts";
import { DictData, UserInfo } from "@/types/types.ts";
import { doFindByDictCode } from "@/api/home";
import { DictCodeEnums } from "@/types/enums.ts";
import { UserAuthVo } from "@/types/vo/UserAuthVo.ts";
import { ElMessage, UploadFile, UploadFiles } from "element-plus"; // 是否显示图片预览弹窗
// 上传组件
let uploadRef = ref();
let form = ref();
// 是否显示图片预览弹窗
let isPreview = ref(false);
// 用户信息
let userInfo = ref<UserInfo>({
  name: "",
  certificatesNo: "",
  certificatesUrl: "",
  certificatesType: "",
} as UserInfo);
// 证件类型
let certificateTypes = ref<DictData[]>([]);
// 用户认证信息
let userAuthVo = reactive<UserAuthVo>({} as UserAuthVo);
onMounted(() => {
  // 获取用户信息
  getUserInfo();
  // 获取证件类型
  getCertificateType();
});

// 获取用户信息
const getUserInfo = async () => {
  let data = await doGetUserInfo();
  if (data === undefined) {
    userInfo.value = {
      name: "",
      certificatesNo: "",
      certificatesUrl: "",
      certificatesType: "",
    };
  } else {
    userInfo.value = data;
  }
  console.log("获取用户信息", userInfo.value);
};
// 获取证件类型
const getCertificateType = async () => {
  let result = await doFindByDictCode(DictCodeEnums.CERTIFICATES_TYPE);
  if (result.code === 200) {
    certificateTypes.value = result.data;
  }
  console.log("获取证件类型", certificateTypes);
};
// 认证用户
const authUserInfo = async () => {
  // 出发表单校验
  let validaRes = await form.value?.validate();
  if (!validaRes) {
    ElMessage.error("请填写完整信息");
    return;
  }
  form.value.clearValidate();
  await doUserAuth(userAuthVo);
  ElMessage.success("认证成功");
  getUserInfo();
};
// 文件数量限制 回调
const fileNumHandler = () => {
  ElMessage.error("只能上传一张图片");
};
// 文件上传成功 回调
const uploadSuccess = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles,
) => {
  userAuthVo.certificatesUrl = response.data;
};
// 文件移除回调
const fileRemove = (uploadFile: UploadFile) => {
  userAuthVo.certificatesUrl = "";
};
// 文件预览回调
const previewFile = (uploadFile: UploadFile) => {
  // 弹窗预览
  isPreview.value = true;
};
// 重写表单数据
const reset = () => {
  // 清除表单数据
  Object.assign(userAuthVo, {
    name: "",
    certificatesNo: "",
    certificatesUrl: "",
    certificatesType: "",
  });
  // 清除文件上传列表
  uploadRef.value?.clearFiles();
};

const rules = {
  name: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        // 使用正则表达式来验证中文名
        // \u4e00-\u9fa5 表示 Unicode 中文字符的范围
        const chineseRegex = /^[\u4e00-\u9fa5]+$/;
        if (!chineseRegex.test(value)) {
          return callback(new Error("请输入中文名"));
        }
        callback();
      },
    },
  ],
  certificatesType: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        let flag = false;
        certificateTypes.value.forEach((item) => {
          if (item.value === value) {
            flag = true;
          }
        });
        if (!flag) {
          return callback(new Error("证件类型不匹配"));
        }
        callback();
      },
    },
  ],
  certificatesNo: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        let sfzReg = /^([1-9]\d{5})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$/;
        let hkbReg = /^\d{9}$/;
        if (sfzReg.test(value) || hkbReg.test(value)) {
          callback();
        }
        callback(new Error("请输入正确的证件号码"));
      },
    },
  ],
  certificatesUrl: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          callback();
        }
        callback(new Error("请上传证件图片"));
      },
    },
  ],
};
</script>

<style lang="scss" scoped>
.box-card {
  .tip {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
    color: #7f7f7f;
  }

  .userInfo {
    width: 50%;
    margin: 20px auto;
  }
}
</style>
